//
//  UIDevice+utils.m
//  storeapp
//
//  Created by huangyi on 12-12-7.
//  Copyright (c) 2012年 ios. All rights reserved.
//

#import "UIDevice+utils.h"
#import "NSString+path.h"
#import "SSKeychain.h"

extern NSString* uniqueID();

@implementation UIDevice (utils)

@end

#import <sys/socket.h>
#import <net/if_dl.h>
#import <ifaddrs.h>
NSString* deviceWifiMAC(){
    void* ifwifi = "en0";
    NSString *result = nil;

    struct ifaddrs * addrs;
    if (getifaddrs(&addrs) == 0) {
        struct ifaddrs * cursor = addrs;
        while (cursor != 0) {
            if (strcmp(ifwifi, cursor->ifa_name) == 0) {
                if (cursor->ifa_addr->sa_family == AF_LINK) {
                    struct sockaddr_dl *addr = (struct sockaddr_dl*)cursor->ifa_addr;
                    unsigned char* hdaddr = (unsigned char*)&addr->sdl_data[addr->sdl_nlen];
                    NSMutableString *mac = [NSMutableString string];
                    for (int i=0; i<addr->sdl_alen; i++) {
                        [mac appendFormat:@"%02x",hdaddr[i]];
                    }
                    if (mac.length) {
                        result = [NSString stringWithString:mac];
                    }
                }
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return result;
}

NSString *const kToolkitKeychain = @"toolkit.device";
NSString *const kToolkitDeviceUniqueID = @"deviceUniqueID";
NSString* deviceUniqueID(){
    NSString *identifierString = [SSKeychain passwordForService:kToolkitKeychain account:kToolkitDeviceUniqueID];
    if (!identifierString) {
        identifierString=uniqueID();
		[SSKeychain setPassword:identifierString forService:kToolkitKeychain account:kToolkitDeviceUniqueID];
    }
	return identifierString;
}
BOOL removeDeviceUniqueID(){
    NSError *error=nil;
    [SSKeychain deletePasswordForService:kToolkitKeychain account:kToolkitDeviceUniqueID error:&error];
    return error?NO:YES;
}

#import <mach/mach.h>
double availableMemory(){
	vm_statistics_data_t vmStats;
	mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
	kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
	if(kernReturn != KERN_SUCCESS) {
		return NSNotFound;
	}
	return ((vm_page_size * vmStats.free_count) / 1024.0) / 1024.0;
}

NSString* deviceAppleID(){
    NSString *appleid=nil;
    @try {
        NSString *path=[[NSBundle mainBundle] bundlePath];
        path=[path stringByDeletingLastPathComponent];
        path=[path stringByAppendingPathComponent:@"iTunesMetadata.plist"];
        NSDictionary *meta=[NSDictionary dictionaryWithContentsOfFile:path];
        meta=[meta valueForKey:@"com.apple.iTunesStore.downloadInfo"];
        meta=[meta valueForKey:@"accountInfo"];
        appleid=[meta valueForKey:@"AppleID"];
    }
    @catch (NSException *exception) {
        NSLog(@"%@",exception.description);
    }
    @finally {
    }
    if (appleid==nil) {
        appleid=[NSString stringWithFormat:@"unknown@%@",[UIDevice currentDevice].name];
    }
    return appleid;
}

NSString* deviceName(){
    //NSString *name=NSUserName();
    //NSString *name=NSFullUserName();
    NSString *name=[UIDevice currentDevice].name;
    return name;
}

NSString* deviceLanguageID(){
    NSString *language=nil;
    NSArray *list=[NSLocale preferredLanguages];
    if (list.count) {
        language=[list objectAtIndex:0];
    }else{
        language=deviceLocaleID();
    }
    language=language.lowercaseString;
    return language;
}
NSString* deviceLocaleID(){
    NSString *locale=nil;
    locale=[[NSLocale currentLocale] localeIdentifier];
    locale=locale.lowercaseString;
    return locale;
}

BOOL deviceIsPad(){
	return [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
}
BOOL deviceIsPhone(){
    return [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone;
}
BOOL deviceIsRetina(){
    CGFloat scale=[UIScreen mainScreen].scale;
    if (scale==2.0) {
        return YES;
    }else{
        return NO;
    }
}
BOOL deviceIsJailbroken(){
    BOOL jailbroken = NO;
	NSString *cydiaPath = @"/Applications/Cydia.app";
	if ([[NSFileManager defaultManager] fileExistsAtPath:cydiaPath]) {
		jailbroken = YES;
	}
	NSString *aptPath = @"/private/var/lib/apt/";
	if ([[NSFileManager defaultManager] fileExistsAtPath:aptPath]) {
		jailbroken = YES;
	}
    if (uniqueID().appPath.isWriteable) {
        jailbroken = YES;
    }
	return jailbroken;
}
BOOL deviceIsSimulator(){
	if (@"release".docPath.isFile) {
		return NO;
	}
	if (@"debug".docPath.isFile) {
		return YES;
	}
	NSString *device = [[UIDevice currentDevice] model];
	if ([device rangeOfString:@"Simulator"].location!=NSNotFound) {
		return YES;
	}else {
		return NO;
	}
}

void RunLoop(NSTimeInterval seconds){
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:seconds]];
    [[UIApplication sharedApplication] endIgnoringInteractionEvents];
}

#import "DDTTYLogger.h"
#import "DDFileLogger.h"
#import "DDASLLogger.h"
#import "DDLog.h"
void DDLogInit(){
    DDFileLogger *fileLogger=[[DDFileLogger alloc] init];
    [DDLog addLogger:fileLogger];
    DDTTYLogger *ttyLogger=[DDTTYLogger sharedInstance];
    [DDLog addLogger:ttyLogger];
}

extern void deviceIsBusy(BOOL busy){
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:busy];
    RunLoop(0.0);
}

void BackgroundTask(dispatch_block_t task){
    static dispatch_queue_t queue=NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue=dispatch_queue_create("background-task-queue", 0);
    });
    UIApplication *app=[UIApplication sharedApplication];
    UIBackgroundTaskIdentifier bgTask=UIBackgroundTaskInvalid;
    bgTask=[app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        NSLog(@"backgroundTask Timeout");
    }];
    dispatch_async(queue, ^{
        task();
        [app endBackgroundTask:bgTask];
        NSLog(@"backgroundTask Finished");
    });
}

void MainTask(dispatch_block_t code){
    if (code) {
        dispatch_async(dispatch_get_main_queue(), ^{
            code();
        });
    }
}

void QueueTask(dispatch_block_t code){
    static dispatch_queue_t queue=NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue=dispatch_queue_create("shared-queue", 0);
    });
    if (code) {
        dispatch_async(queue, code);
    }
}
